package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UnitToProDto;
import com.dg.cuckoo.admin.repository.UnitToProRepository;
import com.dg.cuckoo.admin.service.ProjectInfoServer;
import com.dg.cuckoo.admin.service.UnitToProService;
import com.dg.cuckoo.admin.service.UsertoProjectService;
import com.dg.cuckoo.core.ServiceException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UnitToProServiceimpl implements UnitToProService {
    @Autowired
    private ProjectInfoServer projectInfoServer;
    @Autowired
    private UsertoProjectService usertoProjectService;
    @Autowired
    private UnitToProRepository unitToProRepository;

    @Override
    public String view() {
        String freeVos = JSONObject.fromObject(projectInfoServer.clickUnitInfo()).getString("freeVos");
        String dtos = JSONObject.fromObject(projectInfoServer.clickUnitInfo()).getString("dtos");
        String name = JSONObject.fromObject(usertoProjectService.view()).getString("name");

        JSONObject json = new JSONObject();
        json.put("openUnit",freeVos);//树和数据
        json.put("unit",dtos);  //单位类型为空的
        json.put("name",name);//项目名称的名称list分页
        return json.toString();
    }

    @Override
    public String viewByOpen(String name) {
        return usertoProjectService.openInfoByname(name);
    }

    @Override
    public void save(String unit, List<String> proName) {
        if(unit==null){
            throw new ServiceException("未选择建设单位");
        }
        if(proName.size()>0){
            List<UnitToProDto> dtos = unitToProRepository.findUnitToProDtosByUnit(unit);
            unitToProRepository.deleteAll(dtos);
            for(String s:proName){
                UnitToProDto dto = new UnitToProDto();
                dto.setUnit(unit);
                dto.setProName(s);
                unitToProRepository.save(dto);
            }
        }else {
            List<UnitToProDto> dtos = unitToProRepository.findUnitToProDtosByUnit(unit);
            unitToProRepository.deleteAll(dtos);
        }
    }

    @Override
    public List<String> openUnitInfo(String unit) {
        if(unit==null){
            throw new ServiceException("未选择建设单位");
        }
        List<UnitToProDto> dtos = unitToProRepository.findUnitToProDtosByUnit(unit);
        List<String> list=new ArrayList<>();
        for(UnitToProDto u:dtos){
            list.add(u.getProName());
        }
        return list;
    }
}
